package com.sumc.springcloud.consumer.controller;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.sumc.springcloud.consumer.hystix.MyHystix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * @describe：
 * @author: Smc
 * @version:v1.0 2020/3/20 14:24   Try to write good code
 */
@RestController
public class WebController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("hello")
    public String hello(){
        String body = restTemplate.getForEntity("http://SPRING-CLOUD-EUREKA-PROVIDER/say", String.class).getBody();
        return body;
    }

    @GetMapping("hystrix")
    @HystrixCommand(fallbackMethod = "error",ignoreExceptions = RuntimeException.class,commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3500")
    })
    public String hystrix(){
        return (restTemplate.getForEntity("http://SPRING-CLOUD-EUREKA-PROVIDER/say", String.class).getBody());
    }

    public String error(Throwable throwable){
        System.out.println(throwable.getMessage());
        return "出错了  error:"+throwable.getMessage();
    }

    @GetMapping("hystrixNew")
    public String hystrixNew()throws Exception{
        MyHystix myHystix = new MyHystix(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")),restTemplate);
       //同步调用（该方法执行后，会等待远程返回的结果）
        //String execute = myHystix.execute();
        //异步调用（该方法执行后，不会马上返回结果，将来会有结果）
        Future<String> queue = myHystix.queue();
        //阻塞的方法,直到拿到结果
        String s = queue.get();
        return s;
    }


}
